package com.cino.fullstack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cino.fullstack.entity.User;
import com.cino.fullstack.mapper.UserMapper;
import com.cino.fullstack.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 用户服务实现类
 *
 * @author +Le
 * @since 2025-10-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Page<User> getUserList(Integer pageNum, Integer pageSize, String keyword) {
        Page<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        
        return this.page(page, queryWrapper);
    }

    @Override
    public User getUserById(Long id) {
        if (id == null) {
            return null;
        }
        return this.getById(id);
    }

    @Override
    public boolean saveUser(User user) {
        if (user == null) {
            return false;
        }
        
        // 业务验证
        if (!StringUtils.hasText(user.getName())) {
            throw new IllegalArgumentException("用户名不能为空");
        }

        return this.save(user);
    }

    @Override
    public boolean updateUser(User user) {
        if (user == null || user.getId() == null) {
            return false;
        }
        
        // 检查用户是否存在
        if (!existsUser(user.getId())) {
            throw new IllegalArgumentException("用户不存在");
        }
        
        // 业务验证
        if (!StringUtils.hasText(user.getName())) {
            throw new IllegalArgumentException("用户名不能为空");
        }

        return this.updateById(user);
    }

    @Override
    public boolean deleteUser(Long id) {
        if (id == null) {
            return false;
        }
        
        // 检查用户是否存在
        if (!existsUser(id)) {
            throw new IllegalArgumentException("用户不存在");
        }
        
        return this.removeById(id);
    }

    @Override
    public boolean batchDeleteUsers(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        
        // 检查所有用户是否存在
        for (Long id : ids) {
            if (!existsUser(id)) {
                throw new IllegalArgumentException("用户ID " + id + " 不存在");
            }
        }
        
        return this.removeByIds(ids);
    }

    @Override
    public boolean existsUser(Long id) {
        if (id == null) {
            return false;
        }
        return this.getById(id) != null;
    }

}
